{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# How to train your DragoNN tutorial\n",
    "\n",
    "**Tutorial length**: 25-30 minutes with a CPU.\n",
    "\n",
    "## Outline\n",
    "    * How to use this tutorial\n",
    "    * Review of patterns in transcription factor binding sites\n",
    "    * Learning to localize homotypic motif density\n",
    "    * Sequence model definition\n",
    "    * Training and interpretation of\n",
    "        - single layer, single filter DragoNN\n",
    "        - single layer, multiple filters DragoNN\n",
    "        - Multi-layer DragoNN\n",
    "        - Regularized multi-layer DragoNN\n",
    "    * Critical questions in this tutorial:\n",
    "        - What is the \"right\" way to get insight from a DragoNN model?\n",
    "        - What are the limitations of different interpretation methods?\n",
    "        - Do those limitations depend on the model and the target pattern?\n",
    "    * Suggestions for further exploration\n",
    "\n",
    "Github issues on the dragonn repository with feedback, questions, and discussion are always welcome.\n",
    "\n",
    "\n",
    "## How to use this tutorial\n",
    "\n",
    "This tutorial utilizes a Jupyter/IPython Notebook - an interactive computational enviroment that combines live code, visualizations, and explanatory text. The notebook is organized into a series of cells. You can run the next cell by cliking the play button:\n",
    "![play button](./tutorial_images/play_button.png)\n",
    "You can also run all cells in a series by clicking \"run all\" in the Cell drop-down menu:\n",
    "![play all button](./tutorial_images/play_all_button.png)\n",
    "Half of the cells in this tutorial contain code, the other half contain visualizations and explanatory text. Code, visualizations, and text in cells can be modified - you are encouraged to modify the code as you advance through the tutorial. You can inspect the implementation of a function used in a cell by following these steps:\n",
    "![inspecting code](./tutorial_images/inspecting_code.png)\n",
    "\n",
    "We start by loading dragonn's tutorial utilities and reviewing properties of regulatory sequence that transcription factors bind."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%reload_ext autoreload\n",
    "%autoreload 2\n",
    "#from tutorial_utils import *\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![sequence properties 1](./tutorial_images/sequence_properties_1.jpg)\n",
    "![sequence properties 2](./tutorial_images/sequence_properties_2.jpg)\n",
    "\n",
    "# Learning to localize a homotypic motif density\n",
    "In this tutorial we will learn how to localize a homotypic motif cluster. We will simulate a positive set of sequences with multiple instances of a motif in the center and a negative set of sequences with multiple motif instances positioned anywhere in the sequence:\n",
    "![honotypic motif density localization](./tutorial_images/homotypic_motif_density_localization.jpg)\n",
    "We will then train a binary classification model to classify the simulated sequences. To solve this task, the model will need to learn the motif pattern and whether instances of that pattern are present in the central part of the sequence.\n",
    "\n",
    "We start by getting the simulation data."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Getting simulation data\n",
    "\n",
    "DragoNN provides a set of simulation functions. We will use the simulate_motif_density_localization function to simulate homotypic motif density localization. First, we obtain documentation for the simulation parameters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "    Simulates two classes of seqeuences:\n",
      "        - Positive class sequences with multiple motif instances\n",
      "          in center of the sequence.\n",
      "        - Negative class sequences with multiple motif instances\n",
      "          anywhere in the sequence.\n",
      "    The number of motif instances is uniformly sampled\n",
      "    between minimum and maximum motif counts.\n",
      "\n",
      "    Parameters\n",
      "    ----------\n",
      "    motif_name : str\n",
      "        encode motif name\n",
      "    seq_length : int\n",
      "        length of sequence\n",
      "    center_size : int\n",
      "        length of central part of the sequence where motifs can be positioned\n",
      "    min_motif_counts : int\n",
      "        minimum number of motif instances\n",
      "    max_motif_counts : int\n",
      "        maximum number of motif instances\n",
      "    num_pos : int\n",
      "        number of positive class sequences\n",
      "    num_neg : int\n",
      "        number of negative class sequences\n",
      "    GC_fraction : float\n",
      "        GC fraction in background sequence\n",
      "\n",
      "    Returns\n",
      "    -------\n",
      "    sequence_arr : 1darray\n",
      "        Contains sequence strings.\n",
      "    y : 1darray\n",
      "        Contains labels.\n",
      "    embedding_arr: 1darray\n",
      "        Array of embedding objects.\n",
      "    \n"
     ]
    }
   ],
   "source": [
    "from simulations import simulate_motif_density_localization\n",
    "print(simulate_motif_density_localization.__doc__)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we define parameters for a TAL1 motif density localization in 1500bp long sequence, with 0.4 GC fraction, and 2-4 instances of the motif in the central 150bp for the positive sequences. We simulate a total of 3000 positive and 3000 negative sequences."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "motif_density_localization_simulation_parameters = {\n",
    "    \"motif_name\": \"TAL1_known4\",\n",
    "    \"seq_length\": 1000,\n",
    "    \"center_size\": 150,\n",
    "    \"min_motif_counts\": 2,\n",
    "    \"max_motif_counts\": 4, \n",
    "    \"num_pos\": 3000,\n",
    "    \"num_neg\": 3000,\n",
    "    \"GC_fraction\": 0.4}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We get the simulation data by calling the get_simulation_data function with the simulation name and the simulation parameters as inputs. 1000 sequences are held out for a test set, 1000 sequences for a validation set, and the remaining 4000 sequences are in the training set."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "sequences, y, embed = simulate_motif_density_localization(**motif_density_localization_simulation_parameters)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'numpy.ndarray'> <class 'numpy.ndarray'> <class 'list'>\n",
      "(6000, 1, 4, 1000) (6000, 1) 6000\n",
      "[ 'ATTACCGTAATCTACTATTAAGTCACAACCAAACAATGGATTACTTTCTGCGTTGGAATCAGTGCCGTGCCAATTGCAGTTGTAGTGCAGTATTTTTGGCATGAGCCCGGGCAAAGTTTTATGAAATAAGCAAGAATCCCACCAATGAGTAAATATGGATTGAGCGCGAATTCTCTTCAATATTGATTTGCCAGCAAGACCTTAACTTCAGTTCTGCTATAATATGTCCATGTTAGAAATTTCGTCGAAATGTCATTAGAATAATCAAATATCTTAACAGAATAGCCATTTAAGTGGGAGCAAATCGGTCCCCTTCCGGGAAAAGAAGATCTAGTATATTTCAGTATATACTTTTTGACATGAATTGGTCCCAAGCGACAAATCCGAAGGGCGTACCACGTTAGAAGTATTCGTCTTGTTTGAAAGTAGTCGAACCAGCTGATTGTCAGCTGGTATTAGCAAATAACAATCAGGTGGATTTGCTTGCAATATGTTTAGGCGCGACCCCTGCGCAAAGTTGTCTCTTCAGGCACCCTGTTTCTGGGCGGTTTTTGCATTGATCCAGTCCGAGTGCGGAATAATGCGTAGTTAGAGATTCATTTATGCCTTAGATCTTGAGAATCTATTCACCAAAGTAATTTGCTAGACCCAATCGATCGTTATTCCGTCTTATAAGACACTTAATAAAAAGTGTGCGTGAATGCGGGACCATCGTTTTATATTTAATCCTAGCACTTAGATAACTCATTTCCAGCCTTGAGCTTTTGTTAACGACGATGCACCTGGATCCATCTTTTTTTAGGTTTTCTGCCTGAAGGTACTAAGAAAGGAATGATACTTATGTTCGGTTTTTAATTGCCTTGATCAAGAACTTTGGGGGTTCGCCGGGTAGTTGCCTTGTTTCCTCTCCCACCAAATGATAGTGCTCTCTTAATAAACTCTTAGTGGCTTAGCGAAACTTTGACGAGTATACTAGCTTACTGATCCATGTTAGCTTAAT']\n",
      "[[ True]]\n",
      "pos-433_TAL1_known4-ACCAGCTGAT\n",
      "pos-468_revComp-TAL1_known4-ATCAGGTGGA\n",
      "pos-444_revComp-TAL1_known4-GTCAGCTGGT\n",
      "[None, None, None]\n",
      "X_train.shape\n",
      "(4200, 1, 4, 1000)\n",
      "X_valid.shape\n",
      "(900, 1, 4, 1000)\n",
      "X_test.shape\n",
      "(900, 1, 4, 1000)\n",
      "y_train.shape\n",
      "(4200, 1)\n",
      "y_valid.shape\n",
      "(900, 1)\n",
      "y_test.shape\n",
      "(900, 1)\n",
      "(6000, 1, 4, 1000)\n",
      "[[[1 0 0 1 0 0 0 0 1 1]\n",
      "  [0 0 0 0 1 1 0 0 0 0]\n",
      "  [0 0 0 0 0 0 1 0 0 0]\n",
      "  [0 1 1 0 0 0 0 1 0 0]]]\n"
     ]
    }
   ],
   "source": [
    "import deepchem as dc\n",
    "from utils import one_hot_encode\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "splitter = dc.splits.RandomSplitter()\n",
    "X = one_hot_encode(sequences)\n",
    "\n",
    "X_train, X_rem, y_train, y_rem, embed_train, embed_rem = train_test_split(X, y, embed, test_size=.3)\n",
    "X_valid, X_test, y_valid, y_test, embed_valid, embed_test = train_test_split(X_rem, y_rem, embed_rem, test_size=.5)\n",
    "\n",
    "train = dc.data.NumpyDataset(X_train, y_train)\n",
    "valid = dc.data.NumpyDataset(X_valid, y_valid)\n",
    "test = dc.data.NumpyDataset(X_test, y_test)\n",
    "print(type(X), type(y), type(embed))\n",
    "print(X.shape, y.shape, len(embed))\n",
    "print(sequences[:1])\n",
    "print(y[:1])\n",
    "print([print(emb) for emb in embed[0]])\n",
    "\n",
    "print(\"X_train.shape\")\n",
    "print(X_train.shape)\n",
    "print(\"X_valid.shape\")                                              \n",
    "print(X_valid.shape)\n",
    "print(\"X_test.shape\")                                               \n",
    "print(X_test.shape)\n",
    "print(\"y_train.shape\")                                              \n",
    "print(y_train.shape)\n",
    "print(\"y_valid.shape\")                                              \n",
    "print(y_valid.shape)\n",
    "print(\"y_test.shape\")                                               \n",
    "print(y_test.shape)\n",
    "\n",
    "print(X.shape)\n",
    "print(X[0, :, :, :10])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "simulation_data provides training, validation, and test sets of input sequences X and sequence labels y. The inputs X are matrices with a one-hot-encoding of the sequences:\n",
    "![one hot encoding](./tutorial_images/one_hot_encoding.png)\n",
    "Here are the first 10bp of a sequence in our training data:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[[0, 0, 0, 0, 0, 0, 0, 1, 0, 0],\n",
       "        [0, 0, 0, 1, 0, 0, 1, 0, 1, 1],\n",
       "        [0, 0, 1, 0, 0, 0, 0, 0, 0, 0],\n",
       "        [1, 1, 0, 0, 1, 1, 0, 0, 0, 0]]], dtype=int32)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#simulation_data.X_train[0, :, :, :10]\n",
    "X_train[0, :, :, :10]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This matrix represent the 10bp sequence AAATGGGCCG.\n",
    "\n",
    "# The homotypic motif density localization task\n",
    "The goal of the model is to take the positive and negative sequences simulated above and classify them:\n",
    "![classificatioin task](./tutorial_images/homotypic_motif_density_localization_task.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# DragoNN Models\n",
    "\n",
    "A locally connected linear unit in a DragoNN model can represent a PSSM (part a). A sequence PSSM score is obtained by multiplying the PSSM across the sequence, thersholding the PSSM scores, and taking the max (part b). A PSSM score can also be computed by a DragoNN model with tiled locally connected linear units, amounting to a convolutional layer with a single convolutional filter representing the PSSM, followed by ReLU thersholding and maxpooling (part c).\n",
    "![dragonn vs pssm](./tutorial_images/dragonn_and_pssm.jpg)\n",
    "By utilizing multiple convolutional layers with multiple convolutional filters, DragoNN models can represent a wide range of sequence features in a compositional fashion:\n",
    "![dragonn model figure](./tutorial_images/dragonn_model_figure.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Getting a DragoNN model\n",
    "\n",
    "The main DragoNN model class is SequenceDNN, which provides a simple interface to a range of models and methods to train, test, and interpret DragoNNs. SequenceDNN uses [keras](http://keras.io/), a deep learning library for [Theano](https://github.com/Theano/Theano) and [TensorFlow](https://github.com/tensorflow/tensorflow), which are popular software packages for deep learning.\n",
    "\n",
    "To get a DragoNN model we:\n",
    "    \n",
    "    1) Define the DragoNN architecture parameters\n",
    "        - obtain description of architecture parameters using the inspect_SequenceDNN() function\n",
    "    2) Call the get_SequenceDNN function, which takes as input the DragoNN architecture parameters, and outputs a \n",
    "    randomly initialized DragoNN model."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To get a description of the architecture parameters we use the inspect_SequenceDNN function, which outputs documentation for the model class including the architecture parameters:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "  Sequence DNN models.\n",
      "\n",
      "  Parameters\n",
      "  ----------\n",
      "  seq_length : int \n",
      "      length of input sequence.\n",
      "  num_tasks : int, optional\n",
      "      number of tasks. Default: 1.\n",
      "  num_filters : list[int] | tuple[int]\n",
      "      number of convolutional filters in each layer. Default: (15,).\n",
      "  conv_width : list[int] | tuple[int]\n",
      "      width of each layer's convolutional filters. Default: (15,).\n",
      "  pool_width : int\n",
      "      width of max pooling after the last layer. Default: 35.\n",
      "  L1 : float\n",
      "      strength of L1 penalty.\n",
      "  dropout : float\n",
      "      dropout probability in every convolutional layer. Default: 0.\n",
      "  verbose: bool \n",
      "      Verbose print statements activated if true. \n",
      "  \n"
     ]
    }
   ],
   "source": [
    "#inspect_SequenceDNN()\n",
    "from deepchem.models.tensorgraph.models.sequence_dnn import SequenceDNN\n",
    "print(SequenceDNN.__doc__)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\"Available methods\" display what can be done with a SequenceDNN model. These include common operations such as training and testing the model, and more complex operations such as extracting insight from trained models. We define a simple DragoNN model with one convolutional layer with one convolutional filter, followed by maxpooling of width 35. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "one_filter_dragonn_parameters = {\n",
    "    'seq_length': 1000,\n",
    "    'num_filters': [1],\n",
    "    'conv_width': [10],\n",
    "    'pool_width': 35}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "we get a randomly initialized DragoNN model by calling the get_SequenceDNN function with one_filter_dragonn_parameters as the input"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "seq_dnn = SequenceDNN(1000, num_filters=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Training a DragoNN model\n",
    "\n",
    "Next, we train the one_filter_dragonn by calling train_SequenceDNN with one_filter_dragonn and simulation_data as the inputs. In each epoch, the one_filter_dragonn will perform a complete pass over the training data, and update its parameters to minimize the loss, which quantifies the error in the model predictions. After each epoch, the code prints performance metrics for the one_filter_dragonn on the validation data. Training stops once the loss on the validation stops improving for multiple consecutive epochs. The performance metrics include balanced accuracy, area under the receiver-operating curve ([auROC](https://en.wikipedia.org/wiki/Receiver_operating_characteristic)), are under the precision-recall curve ([auPRC](https://en.wikipedia.org/wiki/Precision_and_recall)), and recall for multiple false discovery rates  (Recall at [FDR](https://en.wikipedia.org/wiki/False_discovery_rate))."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Ending global_step 42: Average loss 0\n",
      "TIMING: model fitting took 79.998 s\n"
     ]
    }
   ],
   "source": [
    "#train_SequenceDNN(one_filter_dragonn, simulation_data)\n",
    "#seq_dnn.build()\n",
    "seq_dnn.fit(train, \"binary_crossentropy\", nb_epoch=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A single layer, single filter model gets good performance and doesn't overfit much. Let's look at the learning curve to demonstrate this visually:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'SequenceDNN_learning_curve' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-11-7d6a6884d584>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mSequenceDNN_learning_curve\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mone_filter_dragonn\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m: name 'SequenceDNN_learning_curve' is not defined"
     ]
    }
   ],
   "source": [
    "SequenceDNN_learning_curve(one_filter_dragonn)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# A multi-filter DragoNN model \n",
    "Next, we modify the model to have 15 convolutional filters instead of just one filter. How does this model compare to the single filter model?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "multi_filter_dragonn_parameters = {\n",
    "    'seq_length': 1000,\n",
    "    'num_filters': [15], ## notice the change from 1 filter to 15 filters\n",
    "    'conv_width': [10],\n",
    "    'pool_width': 35}\n",
    "multi_filter_dragonn = get_SequenceDNN(multi_filter_dragonn_parameters)\n",
    "train_SequenceDNN(multi_filter_dragonn, simulation_data)\n",
    "SequenceDNN_learning_curve(multi_filter_dragonn)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It slightly outperforms the single filter model. Let's check if the learned filters capture the simulated pattern."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "interpret_SequenceDNN_filters(multi_filter_dragonn, simulation_data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Only some of the filters closesly match the simulated pattern. This illustrates that interpreting model parameters directly works partially for multi-filter models. Another way to deduce learned patterns is to examine feature importances for specific examples. Next, we explore methods for feature importance scoring."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Interpreting data with a DragoNN model\n",
    "\n",
    "Using in-silico mutagenesis (ISM) and [DeepLIFT](https://arxiv.org/pdf/1605.01713v2.pdf), we can obtain scores for specific sequence indicating the importance of each position in the sequence. To assess these methods we compare ISM and DeepLIFT scores to motif scores for each simulated motif at each position in the sequence. These motif scores represent the \"ground truth\" importance of each position because they are based on the motifs used to simulate the data. We plot provide comaprisons for a positive class sequence on the left and a negative class sequence on the right."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "interpret_data_with_SequenceDNN(multi_filter_dragonn, simulation_data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the positive example (left side), ISM correctly highlights the two motif instances in the central 150bp. DeepLIFT highlights them as well. DeepLIFT also slightly highlights false positive feature on the left side but its score is sufficiently small that we can discriminate between the false positive feature and the true positive features. In the negative example (right side), ISM doesn't highlight anything but DeepLIFT a couple false positive feature almost as much as it highlights true positive features in the positive example."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# A multi-layer DragoNN model\n",
    "Next, we train a 3 layer model for this task. Will it outperform the single layer model and to what extent will it overfit?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "multi_layer_dragonn_parameters = {\n",
    "    'seq_length': 1000,\n",
    "    'num_filters': [15, 15, 15], ## notice the change to multiple filter values, one for each layer\n",
    "    'conv_width': [10, 10, 10], ## convolutional filter width has been modified to 25 from 45\n",
    "    'pool_width': 35}\n",
    "\n",
    "multi_layer_dragonn = get_SequenceDNN(multi_layer_dragonn_parameters)\n",
    "train_SequenceDNN(multi_layer_dragonn, simulation_data)\n",
    "SequenceDNN_learning_curve(multi_layer_dragonn)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This model performs about the same as the single layer model but it overfits more. We will try to address that with dropout regularization. But first, what do the first layer filters look like?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "interpret_SequenceDNN_filters(multi_layer_dragonn, simulation_data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The filters now make less sense than in the single layer model case. In multi-layered models, sequence features are learned compositionally across the layers. As a result, sequence filters in the first layer focus more on simple features that can be combined in higher layers to learn motif features more efficiently, and their interpretation becomes less clear based on simple visualizations. Let's see where ISM and DeepLIFT get us with this model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "interpret_data_with_SequenceDNN(multi_layer_dragonn, simulation_data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As in the single layer model case, ISM correctly highlights the two true positive features in the positive example (left side) and correctly ignores features in the negative example (right side). DeepLIFT still highlight the same false positive feature example in the positive example as before, but we can still separate it from the true positive features. In the negative example, it still highlights some false positive features."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# A regularized multi-layer DragoNN model\n",
    "Next, we regularize the 3 layer using 0.2 dropout on every convolutional layer. Will dropout improve validation performance?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "regularized_multi_layer_dragonn_parameters = {\n",
    "    'seq_length': 1000,\n",
    "    'num_filters': [15, 15, 15],\n",
    "    'conv_width': [10, 10, 10],\n",
    "    'pool_width': 35,\n",
    "    'dropout': 0.2} ## we introduce dropout of 0.2 on every convolutional layer for regularization\n",
    "regularized_multi_layer_dragonn = get_SequenceDNN(regularized_multi_layer_dragonn_parameters)\n",
    "train_SequenceDNN(regularized_multi_layer_dragonn, simulation_data)\n",
    "SequenceDNN_learning_curve(regularized_multi_layer_dragonn)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As expected, dropout decreased the overfitting this model displayed previously and increased validation performance. Let's see the effect on feature discovery."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "interpret_data_with_SequenceDNN(regularized_multi_layer_dragonn, simulation_data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "ISM now highlights a false positive feature in the positive example (left side) more than the true positive features. What happened? A sufficiently accurate model should not change its confidence that there are 2 or more features in the central 150 base pairs (bps) due to a single bp change. So it makes sense that in the limit of the \"perfect\" model ISM will actually lose its power to discover features in this example.\n",
    "\n",
    "How about DeepLIFT? DeepLIFT correctly highlights the only two positive features in the positive example. So it seems that in the limit of the \"perfect\" model, DeepLIFT gets closer to the true positive features.\n",
    "\n",
    "Why did this happen? Why, as we regularize the model and improve the performance, ISM fails to highlight the true positive features? Here is a hint: in the limit of the \"perfect\" model for this simulation, will a single base pair perturbation to the positive example here change its confidence that it is still a positive example? I encourage you to open github issues on the dragonn repo to discuss these questions.\n",
    "\n",
    "Below is an overview of patterns and simulations for further exploration."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# For further exploration \n",
    "In this tutorial we explored modeling of homotypic motif density. Other properties of regulatory DNA sequence include\n",
    "![sequence properties 3](./tutorial_images/sequence_properties_3.jpg)\n",
    "![sequence properties 4](./tutorial_images/sequence_properties_4.jpg)\n",
    "\n",
    "DragoNN provides simulations that formulate learning these patterns into classification problems:\n",
    "![sequence](./tutorial_images/sequence_simulations.png)\n",
    "\n",
    "You can view the available simulation functions by running print_available_simulations:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print_available_simulations()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [conda env:deepchem]",
   "language": "python",
   "name": "conda-env-deepchem-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
